Vue.component('admin-stock-out-management', {
  data() {
    return {
      stockOutRecords: [],
      products: [],
      loading: false,
      searchForm: {
        product_name: '',
        date_range: []
      },
      dialogVisible: false,
      dialogTitle: '',
      formData: {
        id: null,
        product_id: '',
        quantity: '',
        notes: ''
      },
      formRules: {
        product_id: [
          { required: true, message: '请选择商品', trigger: 'change' }
        ],
        quantity: [
          { required: true, message: '请输入出库数量', trigger: 'blur' },
          { type: 'number', message: '数量必须为数字', trigger: 'blur' }
        ]
      },
      currentPage: 1,
      pageSize: 10,
      total: 0
    };
  },
  methods: {
    async loadStockOutRecords() {
      this.loading = true;
      try {
        const params = {
          page: this.currentPage,
          per_page: this.pageSize
        };
        
        // 处理搜索参数
        if (this.searchForm.product_name) {
          params.search = this.searchForm.product_name;
        }
        
        // 处理日期范围参数
        if (this.searchForm.date_range && this.searchForm.date_range.length === 2) {
          params.start_date = this.searchForm.date_range[0];
          params.end_date = this.searchForm.date_range[1];
        }
        
        const response = await stockOutAPI.getStockOutRecords(params);
        if (response.data && response.data.records) {
          this.stockOutRecords = response.data.records;
          this.total = response.data.pagination.total;
        }
      } catch (error) {
        console.error('获取出库记录失败:', error);
        this.$message.error(error.message || '获取出库记录失败');
      } finally {
        this.loading = false;
      }
    },
    async loadProducts() {
      try {
        const response = await productAPI.getProducts({ page_size: 1000 });
        if (response.data && response.data.products) {
          this.products = response.data.products.map(product => ({
            value: product.id,
            label: product.name,
            stock_quantity: product.stock_quantity
          }));
        }
      } catch (error) {
        console.error('获取商品列表失败:', error);
      }
    },
    handleSearch() {
      this.currentPage = 1;
      this.loadStockOutRecords();
    },
    handleReset() {
      this.searchForm = {
        product_name: '',
        date_range: []
      };
      this.currentPage = 1;
      this.loadStockOutRecords();
    },
    handleAdd() {
      this.dialogTitle = '添加出库记录';
      this.formData = {
        id: null,
        product_id: '',
        quantity: '',
        notes: ''
      };
      this.dialogVisible = true;
    },
    async handleSubmit() {
      try {
        await this.$refs.form.validate();
        
        // 检查库存是否足够
        const selectedProduct = this.products.find(p => p.value === this.formData.product_id);
        if (selectedProduct && this.formData.quantity > selectedProduct.stock_quantity) {
          this.$message.error('出库数量超过库存数量');
          return;
        }
        
        await stockOutAPI.createStockOutRecord(this.formData);
        this.$message.success('出库成功');
        
        this.dialogVisible = false;
        // 重新获取出库记录和商品数据
        await Promise.all([
          this.loadStockOutRecords(),
          this.loadProducts()
        ]);
      } catch (error) {
        console.error('出库失败:', error);
        this.$message.error(error.message || '出库失败');
      }
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.loadStockOutRecords();
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.loadStockOutRecords();
    }
  },
  async mounted() {
    await Promise.all([
      this.loadProducts(),
      this.loadStockOutRecords()
    ]);
  },
  template: `
    <div class="stock-out-management">
      <el-card>
        <div slot="header">
          <span>出库管理</span>
          <el-button type="primary" icon="el-icon-plus" @click="handleAdd" style="float: right;" size="small">
            添加出库记录
          </el-button>
        </div>
        
        <!-- 搜索表单 -->
        <el-form :model="searchForm" inline>
          <el-form-item label="商品名称">
            <el-input v-model="searchForm.product_name" placeholder="请输入商品名称" clearable size="small"></el-input>
          </el-form-item>
          <el-form-item label="出库日期">
            <el-date-picker
              v-model="searchForm.date_range"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              size="small">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleSearch" size="small">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="handleReset" size="small">重置</el-button>
          </el-form-item>
        </el-form>
        
        <!-- 出库记录表格 -->
        <el-table :data="stockOutRecords" v-loading="loading" border>
          <el-table-column prop="product_name" label="商品名称" min-width="100"></el-table-column>
          <el-table-column prop="quantity" label="出库数量" width="100"></el-table-column>
          <el-table-column prop="operator_name" label="操作员" width="100"></el-table-column>
          <el-table-column prop="created_at" label="出库时间" width="150">
            <template slot-scope="scope">
              {{ new Date(scope.row.created_at).toLocaleString() }}
            </template>
          </el-table-column>
          <el-table-column prop="notes" label="备注" min-width="150" show-overflow-tooltip></el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="margin-top: 20px; text-align: right;">
        </el-pagination>
      </el-card>
      
      <!-- 添加出库记录对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="400px">
        <el-form :model="formData" :rules="formRules" ref="form" label-width="100px">
          <el-form-item label="选择商品" prop="product_id">
            <el-select v-model="formData.product_id" placeholder="请选择商品" style="width: 100%;">
              <el-option
                v-for="item in products"
                :key="item.value"
                :label="item.label + ' (库存: ' + item.stock_quantity + ')'"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="出库数量" prop="quantity">
            <el-input-number v-model="formData.quantity" :min="1" style="width: 100%;"></el-input-number>
          </el-form-item>
          <el-form-item label="备注">
            <el-input type="textarea" v-model="formData.notes" :rows="3" placeholder="请输入备注（可选）"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </el-dialog>
    </div>
  `
});
